package com.jader.fragment;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import me.maxwin.view.XListView;
import me.maxwin.view.XListView.IXListViewListener;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jader.activities.Merchant;
import com.jader.activities.Seller;
import com.jader.adapter.MerchantAdapter;
import com.jader.beans.Goods;
import com.jader.db.MyData;
import com.jader.main.MainActivity;
import com.jader.myviews.MyProgressDialog;
import com.jader.util.JaderApplication;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.zlp.jader.R;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;

public class SouYeFragment extends Fragment implements OnClickListener {
	// 声明
	// 写入请求网址
	private String url = JaderApplication.getIP() + "/Jader/client?type="
			+ JaderApplication.SEARCH_NUMBER + "&page=";

	private MerchantAdapter adapter;
	private List<Goods> list = new ArrayList<Goods>();
	private XListView xListView;
	// 商品的四大分类
	ImageView imageView1, imageView2, imageView3, imageView4;
	private View view;
	private FragmentTransaction transaction;
	private FragmentManager manager;
	int page = 10;
	private MyProgressDialog dialog;
	private String time;

	private SQLiteDatabase sqLiteDatabase;
	private MainActivity activity;

	private View emptyView;
	private Button internet_Button;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.activity = (MainActivity) activity;
		manager = this.activity.getSupportFragmentManager();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.souye, null);
		// 初始化布局控件

		initTopBar();
		xListView = (XListView) view.findViewById(R.id.xlist);
		View head = View.inflate(getActivity(),
				R.layout.shouyedetail_list_dingbu, null);
		inintViews(head);
		xListView.addHeaderView(head);
		// 进行web端连接 发送请求
		page = 0;
		dialog = JaderApplication.getMyDialog(getActivity());
		adapter = new MerchantAdapter(list, getActivity());
		xListView.setAdapter(adapter);
		xListView.setPullLoadEnable(true);
		xListView.setXListViewListener(new IXListViewListener() {
			@Override
			public void onRefresh() {
				// 刷新
				page = 0;
				sendRequest(url + page);

			}

			@Override
			public void onLoadMore() {
				// 加载
				page = list.size();
				sendRequest(url + page);

			}
		});
		xListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// 监听首页商品推荐单击事件
				Intent intent = new Intent(getActivity(), Seller.class);
				intent.putExtra("goods", list.get(arg2 - 2));
				startActivity(intent);
			}
		});
		ViewGroup parentView = (ViewGroup) xListView.getParent();
		emptyView = activity.getLayoutInflater().inflate(R.layout.empty, null);
		internet_Button = (Button) emptyView.findViewById(R.id.internet_button);
		internet_Button.setOnClickListener(this);
		parentView.addView(emptyView);
		xListView.setEmptyView(emptyView);
		return view;
	}

	@Override
	public void onResume() {
		if (JaderApplication.isNetworkAvailable(getActivity())) {
			sendRequest(url + page);
		} else {
			sqLiteDatabase = JaderApplication.getSqLiteDatabase();
			String sql = "select * from " + MyData.GOODSLIST_TABLE;
			Cursor cursor = sqLiteDatabase.rawQuery(sql, null);
			list.clear();
			while (cursor.moveToNext()) {
				int i = 0;
				if (i >= 20) {
					break;
				}
				int msg = cursor.getInt(0);
				String desc = cursor.getString(1);
				double price = cursor.getDouble(2);
				String picture = cursor.getString(3);
				String goodsname = cursor.getString(4);
				list.add(new Goods(null,msg, 0, goodsname, price, desc, null,
						picture, 0, 0));
				i++;

			}

			sqLiteDatabase.close();
		}
		super.onResume();
	}

	private void inintViews(View view) {
		// 找到四个文本框
		imageView1 = (ImageView) view.findViewById(R.id.imageview1);
		imageView2 = (ImageView) view.findViewById(R.id.imageview2);
		imageView3 = (ImageView) view.findViewById(R.id.imageview3);
		imageView4 = (ImageView) view.findViewById(R.id.imageview4);
		// 设置文本框的单击事件
		imageView1.setOnClickListener(this);
		imageView2.setOnClickListener(this);
		imageView3.setOnClickListener(this);
		imageView4.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		Intent intent = new Intent(getActivity(), Merchant.class);
		switch (v.getId()) {
		// 和田玉
		case R.id.imageview1:
			startSeller(intent, 1);
			break;
		// 独山玉
		case R.id.imageview2:
			// 跳转到 HeTianActivity.class(传递一个商品id)
			startSeller(intent, 2);

			break;
		// 岫岩玉
		case R.id.imageview3:
			startSeller(intent, 3);
			break;
		// 蓝田玉
		case R.id.imageview4:
			startSeller(intent, 4);
			break;
		case R.id.internet_button:
			Intent internet_intent = new Intent();
			internet_intent.setClassName("com.android.settings",
					"com.android.settings.Settings");
			activity.startActivity(internet_intent);
			break;
		default:
			break;
		}

	}

	private void startSeller(Intent intent, int categoryid) {
		intent.putExtra("categoryid", categoryid);
		startActivity(intent);
	}

	// 发送请求
	private void sendRequest(final String url) {
		if (JaderApplication.isNetworkAvailable(getActivity())) {
			dialog.show();
			JaderApplication.httpUtils.send(HttpMethod.GET, url,
					new RequestCallBack<String>() {

						@Override
						public void onFailure(HttpException arg0, String arg1) {
							fail();
						}

						@Override
						public void onSuccess(ResponseInfo<String> arg0) {
							Gson gson = new Gson();
							Type type = new TypeToken<ArrayList<Goods>>() {
							}.getType();
							List<Goods> list1 = gson
									.fromJson(arg0.result, type);
							for (Goods goods : list1) {
								boolean flag = false;
								for (Goods good2 : list) {
									if (goods.equals(good2)) {
										flag = true;
									}
								}
								if (!flag) {
									list.add(page, goods);
									page++;

								}
								adapter.notifyDataSetChanged();

							}
							onLoad();
							if (dialog.isShowing()) {
								dialog.dismiss();

							}

						}
					});
		} else {
			fail();
		}

	}

	private void fail() {
		onLoad();
		sqLiteDatabase = JaderApplication.getSqLiteDatabase();
		String sql = "select * from " + MyData.GOODSLIST_TABLE;
		Cursor cursor = sqLiteDatabase.rawQuery(sql, null);
		list.clear();
		while (cursor.moveToNext()) {
			int i = 0;
			if (i >= 20) {
				break;
			}
			int msg = cursor.getInt(0);
			String desc = cursor.getString(1);
			double price = cursor.getDouble(2);
			String picture = cursor.getString(3);
			String goodsname = cursor.getString(4);
			list.add(new Goods(null,msg, 0, goodsname, price, desc, null, picture,
					0, 0));
			i++;

		}

		sqLiteDatabase.close();
		JaderApplication.show(getActivity(), "当前网络不可用，请检查网络连接或刷新");
		if (dialog.isShowing()) {
			dialog.dismiss();

		}
	}

	private void initTopBar() {
		// 动态添加顶部菜单栏碎片
		transaction = manager.beginTransaction();
		// 更换首页最顶部
		SouYe_TopFragment fragment = new SouYe_TopFragment();
		transaction.add(R.id.topbar, fragment);
		transaction.commit();

	}

	private void onLoad() {
		xListView.stopRefresh();
		xListView.stopLoadMore();
		if (time == null) {
			xListView.setRefreshTime("刚刚");
		} else {
			xListView.setRefreshTime(time);
		}
		Date date = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		time = df.format(date);
	}

	@Override
	public void onPause() {
		super.onPause();
		sqLiteDatabase = JaderApplication.getSqLiteDatabase();
		String delete = "delete from " + MyData.GOODSLIST_TABLE;
		sqLiteDatabase.execSQL(delete);
		sqLiteDatabase.close();
		for (int i = 0; i < 20; i++) {
			if (i < list.size()) {
				Goods good = list.get(i);
				sqLiteDatabase = JaderApplication.getSqLiteDatabase();
				String sql = "insert into " + MyData.GOODSLIST_TABLE
						+ " values(?,?,?,?,?)";
				String[] texts = { good.getGoodsid() + "", good.getDesc(),
						good.getPrice() + "", good.getPicture(),
						good.getGoodsName() };
				if (texts != null) {
					sqLiteDatabase.execSQL(sql, texts);
				}
				sqLiteDatabase.close();
			}
		}

	}

}
